package com.hdax.search.thread;


import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 多任务组合
 */
public class Text04 {

    public static ExecutorService executorService= Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<String> productImg = CompletableFuture.supplyAsync(() -> {
            System.out.println("商品的图片信息");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return "one.jpg";
        }, executorService);

        CompletableFuture<String> productAttr = CompletableFuture.supplyAsync(() -> {
            System.out.println("商品的属性");
            return "商品属性";
        }, executorService);

        CompletableFuture<String> jieshao = CompletableFuture.supplyAsync(() -> {
            System.out.println("商品的介绍");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return "商品介绍";
        }, executorService);

        /**
         * 1、 CompletableFuture.allOf:三个参数线程都执行完成，就可以往后继续执行
         */
        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.allOf(productImg, productAttr, jieshao);
        voidCompletableFuture.get();//等待所有的线程都执行完成
        System.out.println("获取线程的返回结果"+productImg.get());
        System.out.println("以上线程都执行完成");


        /**
         * CompletableFuture.anyOf：三个线程有一个执行完成就可以往后继续执行
         */
        CompletableFuture<Object> objectCompletableFuture = CompletableFuture.anyOf(productImg, productAttr, jieshao);
        System.out.println("最快执行完成的一个线程的返回值"+objectCompletableFuture.get());
        System.out.println("线程执行完成");


    }
}
